﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using LynxWebLog.Areas.Pages.ViewModels;

namespace LynxWebLog.Areas.Pages.Controllers
{
    [Authorize(Roles = "BlogUser,BlogAdmin")]
    public class PageEntryController : Controller
    {
        private string _blogOwner;
        private string _blogName;
        private BlogSupport blogSupport;
        private HttpClient client;
        protected override void Initialize(RequestContext requestContext)
        {
            ViewBag.Version = " v: " + Assembly.GetExecutingAssembly().GetName().Version;
            ViewBag.CategoryDisplay = false;
            ViewBag.GoogleAdDisplay = false;
            base.Initialize(requestContext);
            this._blogOwner = this.ControllerContext.RouteData.Values["username"].ToString();
            this._blogName = this.ControllerContext.RouteData.Values["blogname"].ToString();
            ViewBag.LegacyBrowser = Request.UserAgent.Contains("iPad; CPU OS 5");
            this.blogSupport = new BlogSupport();
            client = ClientUtility.BlogAPIClient();
        }

        //
        // GET: /Blogs/PostData/
        public async Task<ActionResult> Index()
        {
            HttpResponseMessage resp = await client.GetAsync("api/PageData?$filter=blogid eq '" + _blogOwner + "_" + _blogName + "'");
            resp.EnsureSuccessStatusCode();
            List<PageData> lpd = (await resp.Content.ReadAsAsync<IEnumerable<PageData>>()).ToList();

            resp = await client.GetAsync("api/BlogData/" + _blogOwner + "_" + _blogName);
            resp.EnsureSuccessStatusCode();
            BlogData bd = await resp.Content.ReadAsAsync<BlogData>();

            List<PageEntry> lpe = new List<PageEntry>();
            foreach (PageData pd in lpd) {
                lpe.Add(new PageEntry(pd, bd));
            }

            return View(lpe);
        }

        //
        // GET: /Blogs/PostData/Details/5
        public async Task<ActionResult> Details(int id)
        {
            ViewBag.BlogId = _blogOwner + "_" + _blogName;
            HttpResponseMessage resp = await client.GetAsync("api/PageData/" + id);
            resp.EnsureSuccessStatusCode();
            PageData pd = await resp.Content.ReadAsAsync<PageData>();

            resp = await client.GetAsync("api/BlogData/" + _blogOwner + "_" + _blogName);
            resp.EnsureSuccessStatusCode();
            BlogData bd = await resp.Content.ReadAsAsync<BlogData>();
            ViewBag.License = CC_License.BuildLicenseFlds(pd.license, this.HttpContext);
            
            PageEntry pe = new PageEntry(pd, bd);

            return View(pe);
        }

        //
        // GET: /Blogs/PostData/Create
        public ActionResult Create()
        {
            ViewBag.License = CC_License.BuildLicenseFlds(string.Empty, this.HttpContext);
            ViewBag.BlogId = _blogOwner + "_" + _blogName;
            return View();
        }

        //
        // POST: /Blogs/PostData/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        [MaliciousActivityChecksFilter]
        public async Task<ActionResult> Create(PageEntry pe)
        {
            if (!string.IsNullOrEmpty(pe.dateCreatedString)) {
                pe.pd.DateCreated = DateTime.Parse(pe.dateCreatedString);
            }
            if (ModelState.IsValid) {
                try {
                    MetaWebLogAPI mwApi = new MetaWebLogAPI();
                    int newPageId = await mwApi.NewPage(_blogOwner, string.Empty, _blogOwner + "_" + _blogName, new Page(pe.pd), pe.pd.license);

                    return RedirectToAction("Index", "PageEntry",this.RouteData.Values);
                }
                catch {
                    ViewBag.License = CC_License.BuildLicenseFlds(string.Empty, this.HttpContext);
                    return View(pe);
                }
            }
            return View();
        }

        //
        // GET: /Blogs/PostData/Edit/5
        public async Task<ActionResult> Edit(int id)
        {
            HttpResponseMessage resp = await client.GetAsync("api/PageData/" + id);
            resp.EnsureSuccessStatusCode();
            PageData pd = await resp.Content.ReadAsAsync<PageData>();
            ViewBag.License = CC_License.BuildLicenseFlds(pd.license, this.HttpContext);

            resp = await client.GetAsync("api/BlogData/" + _blogOwner + "_" + _blogName);
            resp.EnsureSuccessStatusCode();
            BlogData bd = await resp.Content.ReadAsAsync<BlogData>();

            PageEntry pe = new PageEntry(pd, bd);

            return View(pe);
        }

        //
        // POST: /Blogs/PostData/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [MaliciousActivityChecksFilter]
        public async Task<ActionResult> Edit(PageEntry pe)
        {
            if (!string.IsNullOrEmpty(pe.dateCreatedString)) {
                pe.pd.DateCreated = DateTime.Parse(pe.dateCreatedString);
            }
            try {
                MetaWebLogAPI mwApi = new MetaWebLogAPI();
                await mwApi.EditPage(_blogOwner, string.Empty, pe.pd.pageid, new Page(pe.pd), pe.pd.license);

                return RedirectToAction("Index", "PageEntry", this.RouteData.Values);
            }
            catch {
                ViewBag.License = CC_License.BuildLicenseFlds(pe.pd.license, this.HttpContext);
                return View(pe);
            }
        }

        //
        // GET: /Blogs/PostData/Delete/5
        public async Task<ActionResult> Delete(int id)
        {
            HttpResponseMessage resp = await client.GetAsync("api/PageData/" + id);
            resp.EnsureSuccessStatusCode();
            PageData pd = await resp.Content.ReadAsAsync<PageData>();

            resp = await client.GetAsync("api/BlogData/" + _blogOwner + "_" + _blogName);
            resp.EnsureSuccessStatusCode();
            BlogData bd = await resp.Content.ReadAsAsync<BlogData>();

            PageEntry pe = new PageEntry(pd, bd);
            ViewBag.License = CC_License.BuildLicenseFlds(pe.pd.license, this.HttpContext);

            return View(pe);
        }

        //
        // POST: /Blogs/PostData/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        [MaliciousActivityChecksFilter]
        public async Task<ActionResult> DeleteConfirmed(int pageid)
        {
            try {
                MetaWebLogAPI mwApi = new MetaWebLogAPI();
                await mwApi.DeletePage(_blogOwner, string.Empty, pageid);

                return RedirectToAction("Index", "PageEntry");
            }
            catch (SystemException ex) {
                Debug.Print(ex.Message);
                return RedirectToAction("Delete", "PageEntry");
            }
        }
    }
}
